package com.jiguang.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiguang.property.dto.HostelInfoDTO;
import com.jiguang.property.dto.NoticeInfoDTO;
import com.jiguang.property.dto.UserInfoDTO;
import com.jiguang.property.entity.HostelInfo;
import com.jiguang.property.entity.NoticeInfo;
import com.jiguang.property.mapper.NoticeInfoMapper;
import com.jiguang.property.service.HostelInfoService;
import com.jiguang.property.service.NoticeInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiguang.property.utils.JwtUtils;
import com.jiguang.property.utils.Result;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2025-03-10
 */
@Service
public class NoticeInfoServiceImpl extends ServiceImpl<NoticeInfoMapper, NoticeInfo> implements NoticeInfoService {
    @Autowired
    private JwtUtils tokenManager;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HostelInfoService hostelInfoService;


    @SneakyThrows
    @Override
    public Result listByCriteria(NoticeInfoDTO noticeInfoDTO) {
        //权限控制
        //通过工具类获取Request对象
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(sra != null){
            HttpServletRequest request = sra.getRequest();
            //获取用户名
            //需要通过解析token获取
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)){
                return Result.error().code(403).message("登陆超时，请重新登陆");
            }
            String userId = tokenManager.getUserFromToken(token);

            //从redis中获取用户信息
            String redisKey = "login:" + userId;
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            String cacheObject = (String) redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isEmpty(cacheObject)) {
                return Result.error().code(403).message("登陆超时，请重新登陆");
            }
            UserInfoDTO ucenter = new ObjectMapper().readValue(cacheObject.toString(), UserInfoDTO.class);

            if (ucenter.getPosition() == 0){
                //获取有的房屋信息
                HostelInfoDTO hostelInfoDTO = new HostelInfoDTO();
                hostelInfoDTO.setUserId(userId);
                List<HostelInfo> hostelInfos = (List<HostelInfo>) hostelInfoService.listHostelInfo(hostelInfoDTO).getData().get("hostelInfos");
                if (!CollectionUtils.isEmpty(hostelInfos)){
                    List<String> hostelIds = new ArrayList<>();
                    for (HostelInfo hostelInfo : hostelInfos) {
                        hostelIds.add(hostelInfo.getBuildId());
                    }
                    if(!CollectionUtils.isEmpty(hostelIds)){
                        noticeInfoDTO.setReceiverIds(String.join(",", hostelIds));
                    }
                }
            }
        }

        List<NoticeInfoDTO> noticeInfoDTOS = baseMapper.listByCriteria(noticeInfoDTO);

        //获取列表总数
        Integer totelByCriteria = baseMapper.getTotelByCriteria(noticeInfoDTO);

        return Result.ok().data("noticeInfoDTO", noticeInfoDTOS).data("total",totelByCriteria);
    }

    @Override
    public Result addOrUpdateNoticeInfo(NoticeInfoDTO noticeInfoDTO) {
        //通过工具类获取Request对象
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //获取用户名
        //需要通过解析token获取
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            return Result.error().code(403).message("登陆超时，请重新登陆");
        }
        String userId = tokenManager.getUserFromToken(token);

        NoticeInfo noticeInfo = new NoticeInfo();
        BeanUtils.copyProperties(noticeInfoDTO,noticeInfo);

        noticeInfo.setPublishUserId(userId);

        //保存公告
        if (StringUtils.isEmpty(noticeInfo.getId())){
            baseMapper.insert(noticeInfo);
        }else{
            baseMapper.updateById(noticeInfo);
        }
        return Result.ok().message("操作成功");
    }

    @Override
    public Result deleteNoticeInfo(String noticeInfoIds) {
        List<String> idList = Arrays.asList(noticeInfoIds.split(","));

        //批量删除
        baseMapper.deleteBatchIds(idList);

        return Result.ok().message("删除成功");
    }
}
